/**
 * 判断父标签是否上a标签
 * @param {*} dom 
 * @returns 
 */
function parentNodeIsADom(dom){
  return dom.parentNode.nodeName.toLocaleLowerCase() === 'a'
}

/**
 * 劫持a标签跳转，防止a标签未设置_blank属性直接刷新当前页面
 */
export const hijackJump = {
  bind: function (el) {
    el.handler = function (event) {
      let target = event.target || event.srcElement;
      // 兼容a标签包裹元素，点击的target不是a标签的问题
      const isANode = target.nodeName.toLocaleLowerCase() === 'a' || parentNodeIsADom(target);

      if (isANode) {
        if (event.preventDefault) {
          event.preventDefault();
        } else {
          window.event.returnValue = true;
        }

        if (parentNodeIsADom(target)) target = target.parentNode;

        const url = target.getAttribute('href');

        url && window.open(url);
      }
    };

    el.addEventListener('click', el.handler);
  },
  unbind: function (el) {
    el.removeEventListener('click', el.handler);
  },
};
